using UnityEngine;

namespace QFramework.Example.Event
{
    public class TypeEventSystemExample : MonoBehaviour
    {
        private ITypeEventSystem _typeEventSystem;

        private void Start()
        {
            _typeEventSystem = new TypeEventSystem();

            // 当 GameObject 销毁时 自动触发注销
            _typeEventSystem.Register<EventA>(eA => { Debug.Log("OnEventA"); })
                .UnRegisterWhenGameObjectDestroyed(gameObject);

            _typeEventSystem.Register<EventB>(OnEventB);

            _typeEventSystem.Register<IEventGroup>(group => { Debug.Log(group.GetType()); })
                .UnRegisterWhenGameObjectDestroyed(gameObject);
        }

        private void Update()
        {
            if (Input.GetMouseButtonDown(0)) _typeEventSystem.Send<EventA>();

            if (Input.GetMouseButtonDown(1))
                _typeEventSystem.Send(new EventB
                {
                    ParamB = 123
                });

            if (Input.GetKeyDown(KeyCode.Space))
            {
                _typeEventSystem.Send<IEventGroup>(new EventC());
                _typeEventSystem.Send<IEventGroup>(new EventD());
            }
        }

        private void OnDestroy()
        {
            _typeEventSystem.UnRegister<EventB>(OnEventB);
            _typeEventSystem = null;
        }

        private void OnEventB(EventB e)
        {
            Debug.Log("OnEventB:" + e.ParamB);
        }

        /// <summary>
        ///     事件A
        /// </summary>
        public struct EventA
        {
        }

        /// <summary>
        ///     事件B
        /// </summary>
        public struct EventB
        {
            public int ParamB;
        }

        /// <summary>
        ///     支持事件的继承
        /// </summary>
        public interface IEventGroup
        {
        }

        public struct EventC : IEventGroup
        {
        }

        public struct EventD : IEventGroup
        {
        }
    }
}